<?php

namespace posts\controller;

require_once("common/model/UserDAL.php");
require_once("login/model/LoginModel.php");
require_once("posts/model/PostDAL.php");
require_once("posts/model/ImageModel.php");
require_once("posts/model/PostModel.php");

class PostController {

	/**
	 * @var posts\view\PostView
	 */
	private $view;
	/**
	 * @var common\model\UserDAL
	 */
	private $user;
	/**
	 * @var login\model\LoginModel
	 */
	private $loginModel;
	/**
	 * @var posts\model\ImageModel
	 */
	private $imageModel;
	/**
	 * @var posts\model\PostModel
	 */
	private $model;
	/**
	 * @var posts\model\PostDAL
	 */
	private $postDAL;

	/**
	 * Initiate member variables with corresponding class object.
	 * @param \posts\view\PostView $view
	 */
	public function __construct(\posts\view\PostView $view, \common\model\BaseDAL $baseDAL) {
		$this->view = $view;
		$this->user = new \common\model\UserDAL($baseDAL);
		$this->loginModel = new \login\model\LoginModel($baseDAL);
		$this->postDAL = new \posts\model\PostDAL($baseDAL);
		$this->model = new \posts\model\PostModel();
	}

	/**
	 * Do post procedure. Get user and post data then insert into database.
	 * @return void
	 */
	public function runPosts() {
		if ($this->view->userPosting()) {
			//get the logged in user
			$currentUser = $this->loginModel->getSessionUser();
			//get the user from the database
			$dbUser = $this->user->getUser($currentUser);
			//get post data from the client
			$post = $this->view->getPostData($dbUser);
			//get file form client
			$image = $this->view->getUploadedFile();
			//initiate image model with uploaded image
			$this->imageModel = new \posts\model\ImageModel($image);
			try {
				$this->model->validatePost($post);
				//validate image
				$this->imageModel->validateImage();
				//if no exceptions are thrown resize and save image
				$this->imageModel->processImage();
				//add new post to database
				
				$this->postDAL->addPost($post, $this->imageModel);				
			} catch (\Exception $e) {
				$this->view->postFailed($post, $image);
			}					
		}
	}
}